package yunplus.io.hchome.utils;

import android.os.Handler;
import android.os.Message;
import android.util.Log;
import java.io.IOException;

import okhttp3.OkHttpClient;
import okhttp3.Request;

/**
 * Created by WangFan on 2017/3/14.
 */

public class NetworkUtils {

    private static final String TAG = "NetworkUtils";
    private static final int WHAT_OK = 0;
    private static final int WHAT_ERROR = -1;

    public static final void ping(final String target, final ICallback callback) {
        final Handler _handler = new Handler(){
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                callback.onStart();
                switch(msg.what){
                    case WHAT_OK:
                        callback.onSuccess(null);
                        return;
                    case WHAT_ERROR:
                        callback.onError(null);
                        return;
                }
                callback.onFinish();
            }
        };

        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    OkHttpClient client = new OkHttpClient();
                    Request request = new Request.Builder().url("http://" + target).build();
                    client.newCall(request).enqueue(new okhttp3.Callback() {
                        @Override
                        public void onFailure(okhttp3.Call call, IOException e) {
                            _handler.sendEmptyMessage(WHAT_ERROR);
                        }
                        @Override
                        public void onResponse(okhttp3.Call call, okhttp3.Response response) throws IOException {
                            _handler.sendEmptyMessage(WHAT_OK);
                        }
                    });
                } catch (Exception e) {
                    _handler.sendEmptyMessage(WHAT_ERROR);
                }
            }
        }).start();

    }
}
